import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Button, Container, Alert } from 'react-bootstrap';

function Register() {
  const [username, setUsername] = useState('');
  const [account, setAccount] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    if (!username || !account || !password) {
      return setError('请填写所有必填字段');
    }

    try {
      const response = await fetch('http://localhost:5000/user/addUser', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, account, password }),
      });

      const data = await response.json();

      if (response.ok) {
        setSuccess(data.message);
        console.log('注册成功');
        alert('注册成功，即将跳转到登录页面');
        // 注册成功，2秒后跳转到登录页面
        setTimeout(() => navigate('/login'), 2000);
      } else {
        setError(data.message);
      }
    } catch (err) {
      setError('无法连接到服务器，请稍后再试');
      console.error('注册错误:', err);
    }
  };

  return (
    <Container className="mt-5" style={{ maxWidth: '400px' }}>
      <h2 className="text-center mb-4">用户注册</h2>
      {error && <Alert variant="danger">{error}</Alert>}
      {success && <Alert variant="success">注册成功,即将跳转到登录页面</Alert>}
      
      <Form onSubmit={handleSubmit}>
        <Form.Group className="mb-3">
          <Form.Label>用户名</Form.Label>
          <Form.Control
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            placeholder="请输入您的用户名"
            required
          />
        </Form.Group>

        <Form.Group className="mb-3">
          <Form.Label>账号</Form.Label>
          <Form.Control
            type="text"
            value={account}
            onChange={(e) => setAccount(e.target.value)}
            placeholder="请输入您的账号"
            required
          />
        </Form.Group>

        <Form.Group className="mb-3">
          <Form.Label>密码</Form.Label>
          <Form.Control
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="请输入您的密码"
            required
          />
        </Form.Group>

        <Button variant="primary" type="submit" className="w-100 mb-3">
          注册
        </Button>
        
        <div className="text-center">
          <Button variant="link" onClick={() => navigate('/login')}>
            已有账号？立即登录
          </Button>
        </div>
      </Form>
    </Container>
  );
}

export default Register;